package dolf.window;

import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XMLHandler {
	private static XMLHandler instance = new XMLHandler();
	private Hashtable<String, Document> table = new Hashtable<String, Document>();
	
	
	private XMLHandler() {
		
	}
	
	public static XMLHandler getInstance() {
		return instance;
	}
	
	public Document getDocument(String s, String entity) {
		if (table.containsKey(s)) return table.get(s);
		//else
		final String en = entity;
		
		InputStream file = this.getClass().getClassLoader().getResourceAsStream(s);
		if (file == null) {
			System.out.println("failed to load XML File "+s);
			return null;
		}
		DocumentBuilder parser = null;
        Document doc = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        
        EntityResolver resolver = new EntityResolver() {
		public InputSource resolveEntity(String publicId, String systemId)
				throws SAXException, IOException {
			InputStream stream = this.getClass().getClassLoader().getResourceAsStream(en);
			InputSource dtd = new InputSource(stream);
			return dtd;
		}
        };
        
        factory.setValidating(true);
        factory.setNamespaceAware(true);
        
        try {
            parser = factory.newDocumentBuilder();
            parser.setEntityResolver(resolver);
            doc = parser.parse(file);
        } catch (SAXException e) {
            System.out.println("sax-exception");
            e.printStackTrace();
        } catch (IOException e) {
        	System.out.println("io-exception");
        	e.printStackTrace();
        } catch (ParserConfigurationException e) {
        	System.out.println("parser-exception");
        	e.printStackTrace();
        }
        table.put(s, doc);
        return doc;
	}
}
